/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.service;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.storage.dao.*;
import com.jeesite.modules.storage.entity.*;
import com.jeesite.modules.storage.util.WebUtil;
import com.jeesite.modules.sys.service.AreaService;
import com.jeesite.modules.sys.service.ConfigService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 活动Service
 */
@Service
@Transactional(readOnly=true)
public class ActivityService extends CrudService<ActivityDao, Activity> {

	@Autowired
	private GoodsDao goodsDao;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsSpecDao goodsSpecDao;

	@Autowired
	private ActivityGoodsService activityGoodsService;

	@Autowired
	private ActivityGoodsDao activityGoodsDao;

	@Autowired
	private ActivityGoodsSpecService activityGoodsSpecService;

	@Autowired
	private ActivityGoodsSpecDao activityGoodsSpecDao;

	@Autowired
	private BrandFocusDao brandFocusDao;

	@Autowired
	private MemberDao memberDao;
	
	/**
	 * 获取单条数据
	 * @param activity
	 * @return
	 */
	@Override
	public Activity get(Activity activity) {
		Activity entity = super.get(activity);
		if (entity != null){
			ActivityGoods activityGoods = new ActivityGoods();
            activityGoods.setActivityId(activity.getId());
			activityGoods.setStatus(ActivityGoods.STATUS_NORMAL);
			entity.setGoodsSpecList(activityGoodsSpecDao.selectGoodsSpecListByActivityId(activity.getId()));
		}
		return entity;
	}
	
	/**
	 * 查询分页数据
	 * @param activity 查询条件
	 * @return
	 */
	@Override
	public Page<Activity> findPage(Activity activity) {
		return super.findPage(activity);
	}

	/**
	 * 查找秒杀价
	 * @param goodsId 商品Id
	 * @param activityGoodsSpecList 活动规格列表
	 */
	private  Double getSeckillPrice(String goodsId,List<ActivityGoodsSpec> activityGoodsSpecList)
	{
		Double seckillPrice = 0d;
		for (ActivityGoodsSpec activityGoodsSpec : activityGoodsSpecList){
			if(ActivityGoodsSpec.STATUS_DELETE.equals(activityGoodsSpec.getStatus()) || !activityGoodsSpec.getGoodsId().equals(goodsId)){
				continue;
			}
			if(activityGoodsSpec.getSeckillPrice() != null && (seckillPrice == 0 ||  activityGoodsSpec.getSeckillPrice() < seckillPrice)){
				seckillPrice = activityGoodsSpec.getSeckillPrice();
			}
		}
		return seckillPrice;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param activity
	 */
//	@Override
	@Transactional(readOnly=false)
	public void save(Activity activity) {
		if(StringUtils.isNotBlank(activity.getId())){
			//活动商品表
			ActivityGoods searchActivityGoods = new ActivityGoods();
			searchActivityGoods.setActivityId(activity.getId());
			List<ActivityGoods> dbActivityGoodsList = activityGoodsDao.findList(searchActivityGoods);
			for (ActivityGoods activityGoods : dbActivityGoodsList){
				activityGoodsDao.phyDelete(activityGoods);
			}

			//活动商品规格表
			ActivityGoodsSpec searchActivityGoodsSpec = new ActivityGoodsSpec();
			searchActivityGoodsSpec.setActivityId(activity.getId());
			List<ActivityGoodsSpec> dbActivityGoodsSpecList = activityGoodsSpecDao.findList(searchActivityGoodsSpec);
			for (ActivityGoodsSpec activityGoodsSpec : dbActivityGoodsSpecList){
				activityGoodsSpecDao.phyDelete(activityGoodsSpec);
			}
		}

		List<String> goodsIdList = ListUtils.newArrayList();
		for (ActivityGoodsSpec activityGoodsSpec : activity.getGoodsSpecList()){
			if(ActivityGoodsSpec.STATUS_DELETE.equals(activityGoodsSpec.getStatus()) || goodsIdList.contains(activityGoodsSpec.getGoodsId())){
				continue;
			}
			goodsIdList.add(activityGoodsSpec.getGoodsId());
		}
		activity.setGoodsNum(goodsIdList.size());
		activity.setNewGoodsNum(goodsIdList.size());

		if(StringUtils.isNotBlank(activity.getThumbnail())){
			String thumbnail = activity.getThumbnail();//"/userfiles/activity/thumbnail/" + UUID.randomUUID() + "." + WebUtil.getExtension(activity.getThumbnail());
//			WebUtil.thumbnails(WebUtil.getRootPath(activity.getThumbnail()),WebUtil.getRootPath(thumbnail));
			activity.setThumbnail(thumbnail);
		}

		if(StringUtils.isNotBlank(activity.getPicture())){
			String[] pictures = activity.getPicture().split("\\|");
			for (Integer i = 0 ; i < pictures.length ; i ++){
				String picture = pictures[i];//"/userfiles/activity/picture/" + UUID.randomUUID() + "." + WebUtil.getExtension(pictures[i]);
//				WebUtil.thumbnails(WebUtil.getRootPath(pictures[i]),WebUtil.getRootPath(picture));
				pictures[i] = picture;
			}
			activity.setPicture(String.join("|",pictures));
		}

		super.save(activity);

		for(String goodsId : goodsIdList){
			Goods goods = goodsDao.get(new Goods(goodsId));
			if(goods == null){
				continue;
			}
			ActivityGoods activityGoods = new ActivityGoods();
			activityGoods.setActivityId(activity.getId());
			activityGoods.setBrandId(goods.getBrandId());
			activityGoods.setCateId(goods.getCateId());
			activityGoods.setGoodsId(goods.getId());
			activityGoods.setCategory(goods.getCategory());
			activityGoods.setThumbnail(goods.getThumbnail());
			activityGoods.setPicture(goods.getPicture());
			activityGoods.setPlatform(goods.getPlatform());
			activityGoods.setCode(goods.getCode());
			activityGoods.setName(goods.getName());
			activityGoods.setMaterial(goods.getMaterial());
			activityGoods.setPlace(goods.getPlace());
			activityGoods.setPrice(goods.getPrice());
			activityGoods.setVipPrice(goods.getVipPrice());
			activityGoods.setMemberPrice(goods.getMemberPrice());
			activityGoods.setAgentPrice(goods.getAgentPrice());
			activityGoods.setSeckillPrice(getSeckillPrice(goods.getId(),activity.getGoodsSpecList()));
			activityGoods.setYear(goods.getYear());
			activityGoods.setSeason(goods.getSeason());

			Integer stockNum = 0;
			for(ActivityGoodsSpec activityGoodsSpec :activity.getGoodsSpecList()) {
				if(ActivityGoodsSpec.STATUS_DELETE.equals(activityGoodsSpec.getStatus()) || !activityGoodsSpec.getGoodsId().equals(goodsId)){
					continue;
				}
				GoodsSpec goodsSpec = goodsSpecDao.get(new GoodsSpec(activityGoodsSpec.getGoodsSpecId()));
				if (goodsSpec == null) {
					activityGoodsSpecDao.phyDelete(activityGoodsSpec);
					continue;
				}
				stockNum += activityGoodsSpec.getStockNum();
			}
			activityGoods.setStockNum(stockNum);
			activityGoods.setSaleNum(0);
			activityGoods.setShareSinglePic(goodsService.getSharePic(null,goodsId,stockNum,"单图",false));
			activityGoods.setShareSingleBuyPic(goodsService.getSharePic(null,goodsId,stockNum,"单图",true));
			activityGoods.setShareMultiplePic(goodsService.getSharePic(null,goodsId,stockNum,"多图",false));
			activityGoods.setShareMultipleBuyPic(goodsService.getSharePic(null,goodsId,stockNum,"多图",true));
			activityGoodsDao.insert(activityGoods);

			Integer activityGoodsSpecsSort = 0;
			for(ActivityGoodsSpec activityGoodsSpec :activity.getGoodsSpecList()){
				if(ActivityGoodsSpec.STATUS_DELETE.equals(activityGoodsSpec.getStatus()) || !activityGoodsSpec.getGoodsId().equals(goodsId)){
					continue;
				}
				GoodsSpec goodsSpec = goodsSpecDao.get(new GoodsSpec(activityGoodsSpec.getGoodsSpecId()));
				if (goodsSpec == null ) {
					activityGoodsSpecDao.phyDelete(activityGoodsSpec);
					continue;
				}
				activityGoodsSpecsSort += 1;
				activityGoodsSpec.setSort(activityGoodsSpecsSort);
				activityGoodsSpec.setBrandId(goods.getBrandId());
				activityGoodsSpec.setActivityId(activity.getId());
				activityGoodsSpec.setCateId(goods.getCateId());
				activityGoodsSpec.setActivityGoodsId(activityGoods.getId());
				activityGoodsSpec.setCode(goodsSpec.getCode());
				activityGoodsSpec.setName(goodsSpec.getName());
				activityGoodsSpec.setColor(goodsSpec.getColor());
				activityGoodsSpec.setPrice(goodsSpec.getPrice());
				activityGoodsSpec.setVipPrice(goodsSpec.getVipPrice());
				activityGoodsSpec.setMemberPrice(goodsSpec.getMemberPrice());
				activityGoodsSpec.setAgentPrice(goodsSpec.getAgentPrice());
				activityGoodsSpec.setRemarks(goodsSpec.getRemarks());
				activityGoodsSpec.setSaleNum(0);
				activityGoodsSpecDao.insert(activityGoodsSpec);
			}
		}
	}
	
	/**
	 * 删除数据
	 * @param activity
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Activity activity) {
		super.delete(activity);
		ActivityGoods activityGoods = new ActivityGoods();
		activityGoods.setActivityId(activity.getId());
		activityGoodsDao.deleteByEntity(activityGoods);
	}

	/*
        获取所有活动
	 * @return 活动列表
    */
	public List<Activity> getAllList(){
		return super.dao.findAllList();
	}

	/**
	 * 获取品牌店铺
	 * @param transMemberId 转发会员Id
	 * @param memberId
	 * @param activityId
	 * @return 品牌店铺
	 */
    public Map getBrand(String transMemberId, String memberId, String activityId) {
		Map map = dao.findById(activityId);
		String brandId = String.valueOf(map.get("brandId"));
		String picture = String.valueOf(map.get("picture"));
		map.put("pictures",StringUtils.isBlank(picture) ? new ArrayList<String>() : picture.split("\\|"));
		map.put("isFocus",brandFocusDao.findExist(transMemberId,memberId,brandId));
		return map;
    }

	/**
	 * 获取活动列表
	 * @param memberId 会员Id
	 * @param activities 活动列表
	 * @return 活动列表
	 */
	private List<Map> getListMaps(String memberId,List<Map> activities){
		String type = memberDao.findTypeById(memberId);
		if(StringUtils.isBlank(type)){
			return  new ArrayList<>();
		}
		List<Map> maps = new ArrayList<>();
		for (Map activityMap : activities) {
			List<Map> goodsList = goodsDao.findListByActivityId(String.valueOf(activityMap.get("activityId")),Integer.MAX_VALUE,1);
			List<Map> goodsMaps = new ArrayList<>();
			for (Map goodsMap : goodsList){
				goodsMap.put("sourcePrice",goodsMap.get("price"));
				goodsMap.put("salePrice",WebUtil.getSalePrice(type, goodsMap));
				goodsMaps.add(goodsMap);
			}
			activityMap.put("goods",goodsMaps);
			maps.add(activityMap);
		}
		return maps;
	}

	/**
	 * 今日上新
	 * @param memberId 会员Id
	 * @param keywords 关键字
	 * @param size 每页数量
	 * @param page 页码
	 * @return 活动列表
	 */
	public List<Map> getSearchMaps(String memberId,String keywords, Integer size, Integer page){
		return getListMaps(memberId,dao.findSearchList(keywords,size * (page - 1),size));
	}

	/**
	 * 今日上新
	 * @param memberId 会员Id
	 * @param size 每页数量
	 * @param page 页码
	 * @return 活动列表
	 */
	public List<Map> getHotMaps(String memberId, Integer size, Integer page){
		return getListMaps(memberId,dao.findHotList(size * (page - 1),size));
	}

	/**
	 * 限时爆款时刻
	 * @return 时刻列表
	 */
	public List<String> getLimitedTimes(){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Date> dates = dao.findLimitedTimes();
		List<String> list = new ArrayList<>();
		for (Date date :dates){
			list.add(simpleDateFormat.format(date));
		}
		return list;
	}

	/**
	 * 即将开售
	 * @param memberId 会员Id
	 * @param size 每页数量
	 * @param page 页码
	 * @return 活动列表
	 */
	public List<Map> getSaleMaps(String memberId, Integer size, Integer page){
		return getListMaps(memberId,dao.findSaleList(size * (page - 1),size));
	}

	/**
	 * 统计汇总【阶段】
	 * @return 统计汇总【阶段】
	 */
	public Map getStages(){
		Map map = new HashMap();
		List<Map> maps = dao.findStages();
		if(maps.size()>0){
			map = maps.get(0);
		}
		return map;
	}

	/**
	 * 查询活动列表
	 * @param type 类型【Hot热播 Sale预告】
	 * @param identity 标识【Today今日 Yesterday昨日 Earlier更早 Tomorrow明日 AfterTomorrow后日】
	 * @param cateId 分类Id
	 * @param size 每页数量
	 * @param page 页码
	 * @return 活动列表
	 */
	public List<Map> getList(String type, String identity,String cateId, Integer size, Integer page){
		List<Map> maps = new ArrayList<>();
		List<Map> activityMaps = dao.findFilterList(type.equals("Hot"),type.equals("Sale"),identity.equals("Today"),identity.equals("Yesterday"),identity.equals("Earlier"),identity.equals("Tomorrow"),identity.equals("AfterTomorrow"), cateId,size * (page - 1),size);
		for(Map activityMap : activityMaps){
			Integer goodsNum = Integer.parseInt(String.valueOf(activityMap.get("goodsNum")));
			Integer newGoodsNum = Integer.parseInt(String.valueOf(activityMap.get("newGoodsNum")));
			NumberFormat numberFormat = NumberFormat.getInstance();
			numberFormat.setMaximumFractionDigits(2);
			activityMap.put("goodsRate", numberFormat.format((float)newGoodsNum/(float)goodsNum*100));
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date startTime = null;
			Date endTime = null;
			try {
				startTime =  simpleDateFormat.parse(String.valueOf(activityMap.get("startTime")));
				endTime =  simpleDateFormat.parse(String.valueOf(activityMap.get("endTime")));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			activityMap.put("days", new Date().before(startTime) ? (startTime.getTime() - new Date().getTime()) /(24*60*60*1000) * -1 : (endTime.getTime() - new Date().getTime()) /(24*60*60*1000));
			maps.add(activityMap);
		}
		return maps;
	}

	/**
	 * 获取Id【类型、品牌、名称、开始时间以及结束时间】
	 * @param type 类型
	 * @param name 名称
	 * @param brandId 品牌Id
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @return 查找Id
	 */
	public String getId(String type, String brandId, String name, Date startTime, Date endTime){
		return dao.findId(type,brandId,name,startTime,endTime);
	}

	/**
	 * 获取品牌Id【Id】
	 * @param activityId 活动Id
	 * @return 品牌Id
	 */
	public String getBrandIdById(@Param("activityId") String activityId){
		return dao.findBrandIdById(activityId);
	}

	/**
	 * 获取类型【Id】
	 * @param activityId 活动Id
	 * @return 类型
	 */
	public String getTypeById(@Param("activityId") String activityId){
		return dao.findTypeById(activityId);
	}

	/**
	 * 获取分享【Id】
	 * @param activityId 活动Id
	 * @return 分享
	 */
	public Map getShareById(@Param("activityId") String activityId){
		return dao.findShareById(activityId);
	}
}
